<template>
	<div class="sessions">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="业务记录管理" name="sessions">
				<div class="session-wrapper" ref="sessionWrapper">
					<div ref="tabelWrapper">
						<Search @searchData="searchData" ref="search" />
						<Table :tableData="sessionsData" @currentChange="viewUserData" id="sessions-table">
							<template v-slot:view>
								<el-table-column width="80px" align="center" label="历史会话">
									<template slot-scope="scope">
										<span
											class="view-button"
											@click="
												e => {
													viewHistory(scope.$index, scope.row, e);
												}
											"
											>查看
										</span>
									</template>
								</el-table-column>
							</template>
							<template v-slot:btn>
								<el-table-column width="200px" align="center" label="操作">
									<!-- 0: '进行中', 1: '待质检', 2: '未完成', 3: '待补录', 4: '质检通过', 5: '补录中'  -->
									<template slot-scope="scope">
										<!-- 进行中和补录中的业务可进行服务监控操作 -->
										<span v-if="['进行中', '补录中'].includes(scope.row.status) && scope.row.media !== 'im'" class="action-button" @click="serviceMonitor(scope.$index, scope.row)"
											>服务监控</span
										>
										<!-- 除未完成、进行中以及补录中的业务外都可进行质检核查 -->
										<span
											v-if="['待质检', '待补录', '质检通过'].includes(scope.row.status) && scope.row.media !== 'im'"
											class="action-button"
											@click="viewInfo(scope.$index, scope.row)"
											>质检核查</span
										>
										<span v-if="['未完成'].includes(scope.row.status) || scope.row.media === 'im'">-</span>
									</template>
								</el-table-column>
							</template>
						</Table>
						<br />
						<PageSize :pages="checkData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
					</div>
					<div class="observer-video-section" v-if="allTokens.length > 0" style="background: #f4f6fc" ref="monitorWrapper">
						<p class="monitor-title">服务监控</p>
						<div class="observer-video-wrapper">
							<div v-for="(tokenInfo, index) in allTokens" :key="tokenInfo.key" class="video-wrapper">
								<div class="video-block">
									<span class="button" @click="closeVideo(index)"><i class="el-icon-close"></i></span>
									<ObserverVideo :token="tokenInfo.token" :agentNo="tokenInfo.agentNo" :key="tokenInfo.token" :streamType="'mixed'" :showStats="false" />
								</div>
							</div>
						</div>
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>
		<SessionHistory
			v-if="showSessionHistory"
			:id="curRecordId"
			:dialogVisible="showSessionHistory"
			:handleClose="
				() => {
					showSessionHistory = false;
				}
			"
		/>
	</div>
</template>

<script>
import Search from './Search.vue';
import Table from './Table.vue';
import PageSize from '../components/PageSize.vue';
import { getBizrecordList, getRoomToken, checkBizrecordStatus } from '@/api/api.js';
import 'splitpanes/dist/splitpanes.css';
import ObserverVideo from '../Monitoring/ObserverVideo.vue';
import SessionHistory from './components/SessionHistory.vue';
import { bizStatus } from './definition';
import { setOperationLogFuntion } from '@/utils/tool.js';
export default {
	components: {
		Search,
		Table,
		PageSize,
		ObserverVideo,
		SessionHistory
	},
	data() {
		return {
			activeName: 'sessions',
			// {page, pageSize, bizScenarioName, status, startTime, endTime}
			checkData: {
				page: 1,
				pageSize: 10,
				total: 0,
				id: '',
				businessflowId: '',
				bizScenarioName: '',
				status: '',
				startTime: '',
				endTime: '',
				customerName: '',
				agentName: '',
				sessionId: ''
			},
			sessionsData: {
				sort: false,
				// 业务记录ID | 业务流水ID | 业务场景 | 最近受理时间 | 访客ID | 坐席ID | 坐席姓名 | 业务状态 | 最新会话 | 历史会话 | 操作
				tableHead: [
					{
						label: '业务记录ID',
						prop: 'id',
						width: '100px'
					},
					{
						label: '业务流水ID',
						prop: 'businessflowId',
						width: '180px'
					},
					{
						label: '业务场景',
						prop: 'bizscenarioName',
						width: '250px'
					},
					{
						label: '最近受理时间',
						prop: 'createdAt',
						width: '180px'
					},
					{
						label: '访客ID',
						prop: 'customerName',
						width: '120px'
					},
					{
						label: '坐席ID',
						prop: 'agentName',
						width: '120px'
					},
					{
						label: '坐席姓名',
						prop: 'fullName',
						width: '120px'
					},
					{
						label: '业务状态',
						prop: 'status',
						width: '80px'
					},
					{
						label: '最新会话',
						prop: 'sessionId',
						width: '180px'
					}
				],
				tableConent: [],
				showIndex: false
			},
			allTokens: [],
			showVideo: false,
			showSessionHistory: false,
			curRecordId: '',
			videoMinHeight: 200,
			paneHeight: 0
		};
	},
	watch: {
		showVideo(newVal, oldVal) {
			if (newVal && !oldVal) {
				this.$nextTick(() => {
					this.resizeTable();
				});
			} else if (oldVal && !newVal) {
				this.$nextTick(() => {
					this.resizeTable();
				});
			}
		}
	},
	mounted() {
		this.getSessionList();
		const pane = document.getElementById('pane-sessions');
		this.paneHeight = pane.clientHeight;
	},

	methods: {
		searchData(query) {
			console.warn('searchData : ', query);
			const { pageSize } = this.checkData;
			this.checkData = Object.assign({}, query, { page: 1, pageSize: pageSize, total: 0 });
			this.getSessionList();
		},
		// 初始化获取 sessions 数据
		getSessionList() {
			this.$Spin.show();
			this.sessionsData.tableConent = [];
			getBizrecordList(this.checkData)
				.then(res => {
					if (res.data && res.data.code === 200) {
						const { data, count } = res.data.message;
						this.sessionsData.tableConent = data.map(item => {
							const { customerName, agentName } = this.getClients(item.bizrecord_clients);
							const { createdAt } = item.session;
							let fullNameList = item.bizrecord_clients.filter(value => {
								return value.fullName && value.role === 'agent';
							}).map(value => {
								return value.fullName;
							});
							return {
								fullName: fullNameList.length > 0 ? fullNameList.toString() : '-',
								id: item.id, // 业务记录ID
								sessionId: item.sessionId, // 会话id
								bizscenarioName: item && item.bizscenarioName ? item.bizscenarioName : '-',
								businessflowId: item.businessflowId,
								createdAt: createdAt ? this.$moment(createdAt).format('YYYY-MM-DD HH:mm:ss') : '-',
								updatedAt: item.updatedAt ? this.$moment(item.updatedAt).format('YYYY-MM-DD HH:mm:ss') : '-',
								status: bizStatus[item.status],
								version: item.version?.toFixed(1) || '',
								name: item.bizscenario && item.bizscenario.name ? item.bizscenario.name : '-',
								roomId: item.session.roomId,
								customerName: customerName,
								agentName: agentName,
								media: item?.session?.media
							};
						});
						this.checkData.total = count;
						console.warn('this.sessionsData.tableConent ', this.sessionsData.tableConent);
					} else {
						console.error('业务记录列表', res.data);
						this.$message.warning('获取业务记录列表失败');
					}
				})
				.catch(err => {
					console.error('业务记录列表', err);
					this.$message.warning('获取业务记录列表失败');
				})
				.finally(() => {
					this.$Spin.hide();
					this.resizeTable();
				});
		},

		// 改变每页条数
		changePageSize(val) {
			this.checkData.pageSize = val;
			this.getSessionList();
		},
		// 改变当前页数
		changeCurrentPage(val) {
			this.checkData.page = val;
			this.getSessionList();
		},
		// 查看详情
		async viewInfo(index, row) {
			console.log(index, row);
			// 检测当前状态
			const result = await checkBizrecordStatus(row.id); // id | businessflowId
			const status = result.data.message?.status;
			if (![1, 3, 4].includes(status)) {
				// 0: '进行中', 1: '待质检', 2: '未完成', 3: '待补录', 4: '质检通过', 5: '补录中'
				this.$message.warning('业务在补录中，无法进行质检核查！');
				return;
			}
			// 新开标签页跳转至双录详情页面
			let routerdata = this.$router.resolve({
				name: 'inspection'
			});
			let newhref = routerdata.href + '?sessionId=' + row.id + '&uid=' + window.uid;
			window.open(newhref, '_blank');
		},

		async serviceMonitor(index, row) {
			console.log(index, row);
			if (!row.roomId) {
				this.$message.warning('会话还未接通，请稍后再试！');
				return;
			}
			const filtered = this.allTokens.filter(item => item.roomId === row.roomId);
			if (filtered && filtered.length > 0) {
				this.$message.warning('该服务已在监控中');
				return;
			}
			// 检测当前状态
			const result = await checkBizrecordStatus(row.id); // id | businessflowId
			const status = result.data.message?.status;
			if (![0, 5].includes(status)) {
				// 0: '进行中', 1: '待质检', 2: '未完成', 3: '待补录', 4: '质检通过', 5: '补录中'
				this.$message.warning('业务已结束，无法进行服务监控！');
				return;
			}
			getRoomToken(row.roomId)
				.then(res => {
					console.log('token：', res);
					this.allTokens.push({
						roomId: row.roomId,
						token: res.data,
						agentNo: row.agentName,
						isChoose: '',
						serviceNo: row.serviceNo,
						key: new Date().getTime()
					});
					this.showVideo = true;
					this.setServiceMonitoringOperationLog(row.agentName, row.id);
				})
				.catch(error => {
					this.$requestApiError(error.response, () => {
						this.$router.push('/');
					});
					this.$message.warning('获取token失败');
				});
		},
		resizeTable() {
			const searchHeight = this.$refs.search.$el.clientHeight + 50;
			const table = document.getElementById('sessions-table');
			const pane = document.getElementById('pane-sessions');
			let height = pane.clientHeight - searchHeight;
			if (this.showVideo) {
				height = pane.clientHeight - searchHeight - this.videoMinHeight;
				if (height < 192) {
					height = 192;
					pane.parentNode.style.overflowY = 'auto';
					pane.style.height = searchHeight + height + this.videoMinHeight + 'px';
				}
				this.$refs.tabelWrapper.style.height = pane.clientHeight - 200 + 'px';
				this.$refs.monitorWrapper.style.height = '200px';
			} else {
				height = this.paneHeight - searchHeight;
				pane.style.height = this.paneHeight + 'px';
			}
			table.style.height = Math.min(height, Math.min(this.checkData.pageSize, this.sessionsData.tableConent.length) * 48 + 55) + 'px';
			if (this.sessionsData.tableConent.length <= 0) {
				table.style.height = '110px';
			}
			table.style.overflowY = 'auto';

			console.warn('table.style.height : ', table.style.height);
		},
		viewHistory(index, row, event) {
			event.preventDefault();
			console.log(index, row);
			this.curRecordId = row.id;
			this.showSessionHistory = true;
		},
		closeVideo(index) {
			console.log('closeVideo', index);
			this.allTokens.splice(index, 1);
			this.showVideo = this.allTokens.length > 0;
		},
		getClients(clients) {
			let customerName = '-';
			let agentName = '-';
			if (!clients) {
				return { customerName, agentName };
			}
			let customers = [];
			let agents = [];
			clients.map(item => {
				if (item.role === 'customer') {
					customers.push(item.userName);
				} else {
					agents.push(item.userName);
				}
			});
			if (customers.length > 0) {
				customerName = customers.join(',');
			}
			if (agents.length > 0) {
				agentName = agents.join(',');
			}
			return { customerName, agentName };
		},

		//设置服务监控运营操作留痕
		setServiceMonitoringOperationLog(userName, id) {
			let agentName = userName.split(',');
			let newAgentName = '';
			agentName.forEach(item => {
				newAgentName = newAgentName + `<${item.trim()}>`;
			});
			setOperationLogFuntion({ type: '1', category: 'serviceMonitoring', content: `监控坐席：${newAgentName}服务，业务记录ID：<${id}>` });
		}
	}
};
</script>

<style lang="less" scoped>
.time {
	color: #666;
	padding-bottom: 20px;
}
.sessions {
	height: 100%;
	.el-tabs {
		height: 100%;
	}
	/deep/ .el-tabs__content {
		height: calc(100% - 60px);
	}
	.el-tab-pane {
		height: 100%;
	}
	.splitpanes__pane {
		background-color: #fff !important;
	}
	.monitor-title {
		font-size: 14px;
		font-weight: 500;
		color: #222222;
		line-height: 24px;
		margin: 10px 10px 0 10px;
	}
	.observer-video-section {
		width: 100%;
		height: 208px;
		overflow-x: auto;
		overflow-y: hidden;
	}
	.observer-video-wrapper {
		display: flex;
		flex-wrap: nowrap;
		height: 165px;
		width: 100%;
		background: #f4f6fc;
		// overflow-x: auto;
		// overflow-y: hidden;

		.video-wrapper {
			width: 260px;
			min-width: 260px;
			height: 165px;
			display: flex;
		}

		.video-block {
			position: relative;
			display: flex;

			.button {
				display: inline-block;
				position: absolute;
				top: 10px;
				right: 13px;
				z-index: 1;
				width: 22px;
				height: 22px;
				background: #99999966;
				border-radius: 50%;
				cursor: pointer;
				text-align: center;
				padding: 2px;
			}
			.el-icon-close {
				color: #fff;
				font-size: 18px;
				height: 22px;
			}
		}

		.observer-video {
			width: 100% !important;
			height: 200px !important;
		}
		/deep/ .streamvideo {
			height: 100%;
		}
		/deep/ video {
			height: calc(100% - 20px);
			background: #000;
			object-fit: fill;
		}
	}

	.view-button {
		font-weight: 400;
		color: #676a6c;
		line-height: 16px;
		cursor: pointer;
	}
	.action-button {
		font-weight: 400;
		color: #6384fe;
		line-height: 16px;
		cursor: pointer;
		margin: 0 10px;
	}
	.session-wrapper {
		display: flex;
		flex-direction: column;
	}
}
</style>

<style lang="less">
.time {
	.el-date-editor {
		input {
			height: 32px;
		}
		.el-input__icon {
			line-height: 32px;
		}
	}
}
</style>
